package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.jsonwebtoken.Claims;
import io.minio.credentials.Jwt;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private SystemUserService systemUserService;
    @Autowired
    private SystemUserMapper systemUserMapper;

    @Override
    public CaptchaVo cpatcha() {
//        设置验证码的参数
        SpecCaptcha specCaptcha = new SpecCaptcha(300, 200, 4);
//        设置验证码内部的内容格式
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
//        获取验证码的内容
        String text = specCaptcha.text();
//        将验证码图片转化
        String base64 = specCaptcha.toBase64();
//        设置redis中的key
        String key ="admin:"+ UUID.randomUUID().toString().replaceAll("-", "");
//        将key和验证码内容上传到redis
        redisTemplate.opsForValue().set(key,text,60, TimeUnit.SECONDS);
//        将验证码图片和key加载到包装类并上传到前端
        CaptchaVo captchaVo = new CaptchaVo(base64, key);
        return captchaVo;
    }

    @Override
    public String login(LoginVo loginVo) {
//        判断用户名是否正确 如果不正确就抛出异常
        LambdaUpdateWrapper<SystemUser> systemUserLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        systemUserLambdaUpdateWrapper.eq(SystemUser::getUsername,loginVo.getUsername());
        SystemUser systemUser = systemUserService.getOne(systemUserLambdaUpdateWrapper);
        if (ObjectUtils.isEmpty(systemUser)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
//        判断密码是否正确,如果不正确就抛出异常
        if(!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
//        判断用户状态
        BaseStatus status = systemUser.getStatus();
        if (status ==BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCESS_FORBIDDEN);
        }
//       判断验证码是否超时
        String str = (String)redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if(str == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
//        判断验证码是否正确
        if(!str.equalsIgnoreCase(loginVo.getCaptchaCode())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        String token = JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
        return token;
    }

    @Override
    public SystemUserInfoVo info(String accessToken) {
//        验证和解析access_token
        Claims claims = JwtUtil.parseToken(accessToken);
//        获取token中的用户id
        Long id = Long.parseLong(claims.get("userId")+"");
        LambdaUpdateWrapper<SystemUser> systemUserLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        systemUserLambdaUpdateWrapper.eq(SystemUser::getId,id);
        SystemUser systemUser = systemUserService.getOne(systemUserLambdaUpdateWrapper);
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getUsername());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }
}
